<?php

namespace addons\AppVersions\api\controllers;

use Yii;
use api\controllers\OnAuthController;
use common\enums\StatusEnum;
use common\helpers\StringHelper;
use addons\AppVersions\common\models\AppVersions;

/**
 * Class VersionsController
 * @package addons\AppVersions\api\controllers
 * @author YiiFrame <21931118@qq.com>
 */
class VersionsController extends OnAuthController
{
    /**
     * @var AppVersions
     */
    public $modelClass = AppVersions::class;

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['index'];

    /**
     * @return array|bool|\yii\data\ActiveDataProvider|\yii\db\ActiveRecord|null
     */
    public function actionIndex()
    {
        $type = Yii::$app->request->get('type', 1);
        $version = Yii::$app->request->get('version');
        $cate_name = Yii::$app->request->get('cate_name');
        $version_id = StringHelper::strToInt($version);
        if ($version_id === false) {
            return false;
        }

        // 设备当前版本号
        $appVersion = AppVersions::find()
            ->where(['type' => $type, 'version_id' => $version_id])
            ->andFilterWhere(['cate_name' => $cate_name])
            ->cache(60)
            ->one();
        // 最新的版本
        $latestAppVersion = AppVersions::find()
            ->where(['status' => StatusEnum::ENABLED, 'type' => $type])
            ->andFilterWhere(['>', 'version_id', $version_id])
            ->andFilterWhere(['cate_name' => $cate_name])
            ->cache(60)
            ->orderBy('id desc')
            ->asArray()
            ->one();

        if ($version_id == $latestAppVersion['version_id']) {
            return false;
        }

        // 如果当前版本不是强制更新的检测历史中有没有强制更新的
        if ($appVersion && $latestAppVersion && $latestAppVersion['is_enforce'] == StatusEnum::DISABLED) {
            $history = AppVersions::find()
                ->where(['status' => StatusEnum::ENABLED, 'type' => $type, 'is_enforce' => StatusEnum::ENABLED])
                ->andWhere(['>', 'id', $appVersion['id']])
                ->andWhere(['<', 'id', $latestAppVersion['id']])
                ->andFilterWhere(['cate_name' => $cate_name])
                ->orderBy('id desc')
                ->cache(60)
                ->asArray()
                ->one();

            $history && $latestAppVersion['is_enforce'] = StatusEnum::ENABLED;
        }

        return $latestAppVersion;
    }

    /**
     * @param $id
     * @return int|\yii\db\ActiveRecord
     */
    public function actionView($id)
    {
        return AppVersions::updateAllCounters(['download_num' => 1], ['id' => $id]);
    }
}